import CryptoJS from 'crypto-js'
let defaultHost = import.meta.env.VITE_BASE_HOST
/// 加密方法
function Encrypt(data) {
    let password = `\0\0\0${defaultHost.slice(3, 8)}\0\0\0\0\0\0\0\0`
    const key = CryptoJS.enc.Utf8.parse(password)
    const iv = CryptoJS.enc.Utf8.parse(password)
    const encrypted = CryptoJS.AES.encrypt(JSON.stringify(data), key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    })
    return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(encrypted.toString()))
}

function Decrypt(encryptedData) {
    let password = `\0\0\0${defaultHost.slice(3, 8)}\0\0\0\0\0\0\0\0`
    const key = CryptoJS.enc.Utf8.parse(password)
    const iv = CryptoJS.enc.Utf8.parse(password)

    // 第一步：解析输入的 Base64 字符串，还原为 UTF-8 字符串
    const utf8String = CryptoJS.enc.Base64.parse(encryptedData).toString(CryptoJS.enc.Utf8)

    // 第二步：解析还原的字符串为加密的 WordArray
    const encryptedWordArray = CryptoJS.enc.Base64.parse(utf8String)

    // 解密数据
    const decrypted = CryptoJS.AES.decrypt({ ciphertext: encryptedWordArray }, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    })

    // 转换解密结果为字符串
    const originalString = decrypted.toString(CryptoJS.enc.Utf8)
    if (!originalString) throw new Error('Decryption failed')

    return JSON.parse(originalString)
}

function SetLocalData(key, value) {
    localStorage.setItem(Encrypt(key), Encrypt(value))
}

function GetLocalData(key) {
    if (localStorage.getItem(Encrypt(key))) {
        return Decrypt(localStorage.getItem(Encrypt(key)))
    }
}

function ClearLocalData(key) {
    localStorage.removeItem(Encrypt(key))
}

function convertToHexSecretKey(host) {
    const hash = CryptoJS.SHA256(host)
    return hash.toString(CryptoJS.enc.Hex)
}

export default {
    Decrypt,
    Encrypt,
    SetLocalData,
    GetLocalData,
    ClearLocalData
}
